﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;

namespace RioLinx.SharePoint.Responsive.Foundation
{
    public partial class CreatePage : LayoutsPageBase
    {
        string L_GeneralError_Text = "An error has occurred.";

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SPWeb spWeb = SPControl.GetContextWeb(Context);
                SPSite spServer = SPControl.GetContextSite(Context);
                // Make sure that the user is authenticated
                //SPUtility.EnsureSessionCredentials(SPSessionCredentialsFlags.RequireAuthentication);
                SPUtility.EnsureAuthentication(spWeb);
                // Create the select drop down control for the available Document Libraries only when the page is first loaded
                if (!Page.IsPostBack)
                {
                    SPListCollection spLists = spWeb.Lists;
                    spLists.IncludeRootFolder = true;
                    int iIndex = 0;
                    System.Collections.Generic.SortedList<string, SPList> assetLibs = new System.Collections.Generic.SortedList<string, SPList>();
                    System.Collections.Generic.SortedList<string, SPList> notAssetLibs = new System.Collections.Generic.SortedList<string, SPList>();

                    string curListID = string.Empty;

                    if(!string.IsNullOrEmpty(Request.Params["List"]))
                        curListID = Request.Params["List"];

                    bool bDocLibAvailable = false;
                    for (int i = 0; i < spLists.Count; i++)
                    {
                        SPList spList = spLists[i];
                        SPDocumentLibrary spDocLib = spList as SPDocumentLibrary;
                        if ((!spList.Hidden) && (spList.BaseType == SPBaseType.DocumentLibrary) && spDocLib != null && !spDocLib.IsCatalog && (spList.BaseTemplate != SPListTemplateType.PictureLibrary))
                        {
                            bool bHasPermission = false;
                            bool oldState = spServer.CatchAccessDeniedException;
                            try
                            {
                                spServer.CatchAccessDeniedException = false;
                                bHasPermission = spList.Permissions.DoesUserHavePermissions(SPRights.AddListItems);
                            }
                            catch (UnauthorizedAccessException)
                            {
                            }
                            finally
                            {
                                spServer.CatchAccessDeniedException = oldState;
                            }
                            if (bHasPermission)
                            {
                                bDocLibAvailable = true;
                                if (spList.IsSiteAssetsLibrary)
                                {
                                    assetLibs.Add(spList.Title, spList);
                                }
                                else
                                {
                                    notAssetLibs.Add(spList.Title, spList);
                                    iIndex++;
                                }

                            }
                        }


                    }

                    foreach (System.Collections.Generic.KeyValuePair<string, SPList> oneEntry in assetLibs)
                    {

                        // If no document library is available, disable the select drop down, and renders a link to create a document library
                        if (iIndex == 0)
                        {
                            string L_NoneAvailable_Text = "None Available";
                            onetidDocLibIDSelect.Disabled = true;
                            ListItem li2 = new ListItem(L_NoneAvailable_Text);
                            onetidDocLibIDSelect.Items.Add(li2);
                            //string L_CreateDocLib1_Text = "Create a new ";
                            //string L_CreateDocLib2_Text = "Document Library";
                            //onetidCreateDocLibLabel.Text = L_CreateDocLib1_Text;
                            //onetidCreateDocLibLink.HRef = "new.aspx?ListTemplate=101&ListBaseType=1";
                            //onetidCreateDocLibLink.InnerText = L_CreateDocLib2_Text;
                            //btnCreate.Enabled = false;
                        }
                        SPList spList = oneEntry.Value as SPList;
                        string value = SPEncode.HtmlEncode(spList.ID.ToString("B").ToUpper());
                        // ListItem encodes the text already, so no HTML encode here is needed
                        string text = spList.Title;
                        ListItem li = new ListItem(text, value);
                        if (value == curListID)
                        {
                            li.Selected = true;
                        }
                        onetidDocLibIDSelect.Items.Add(li);

                    }

                    foreach (System.Collections.Generic.KeyValuePair<string, SPList> oneEntry in notAssetLibs)
                    {

                        // If no document library is available, disable the select drop down, and renders a link to create a document library
                        if (iIndex == 0)
                        {
                            string L_NoneAvailable_Text = "None Available";
                            onetidDocLibIDSelect.Disabled = true;
                            ListItem li2 = new ListItem(L_NoneAvailable_Text);
                            onetidDocLibIDSelect.Items.Add(li2);
                            //string L_CreateDocLib1_Text = "Create a new ";
                            //string L_CreateDocLib2_Text = "Document Library";
                            //onetidCreateDocLibLabel.Text = L_CreateDocLib1_Text;
                            //onetidCreateDocLibLink.HRef = "new.aspx?ListTemplate=101&ListBaseType=1";
                            //onetidCreateDocLibLink.InnerText = L_CreateDocLib2_Text;
                            //btnCreate.Enabled = false;
                        }
                        SPList spList = oneEntry.Value as SPList;
                        string value = SPEncode.HtmlEncode(spList.ID.ToString("B").ToUpper());
                        // ListItem encodes the text already, so no HTML encode here is needed
                        string text = spList.Title;
                        ListItem li = new ListItem(text, value);
                        if (value == curListID)
                        {
                            li.Selected = true;
                        }
                        onetidDocLibIDSelect.Items.Add(li);

                    }


                }
                else // If the form posts back then we assume users press to enter button to create Web Part Pages
                {
                    CreateWebPartPage();
                }
            }
            catch
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                CreateWebPartPage();
            }
            catch
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
        }

        private void CreateWebPartPage()
        {
            SPWeb spWeb = SPControl.GetContextWeb(Context);
            string templateName = Request.Form["WebPartPageTemplate"];
            // Validate the source file name
            if (templateName == null)
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            templateName = templateName.Trim();  // get rid of white spaces
            if (templateName.Length == 0)
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            templateName = templateName + ".aspx";
            if (templateName.Length > SPUtility.MaxLeafNameLength)
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            // Avoid characters like "..\..\" in the path 
            if (templateName != System.IO.Path.GetFileName(templateName))
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            // Validate target file name
            string fileName = Request.Form["Title"];
            if (fileName == null)
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            fileName = fileName.Trim();  // get rid of white spaces
            if (fileName.Length == 0)
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            // Avoid characters like "..\..\" in the path 
            if (fileName != System.IO.Path.GetFileName(fileName))
            {
                Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
                return;
            }
            // Prepare the source file, assuming the Web Part Page templates live in <Installation Path>\Template\<LCID>\<web template>\doctemp\smartpgs
            string sourceFilePath = SPUtility.GetVersionedGenericSetupPath("Template\\", 15) +

                "\\Layouts\\PageTemplates\\";
            sourceFilePath = sourceFilePath + templateName;
            Response.Write(sourceFilePath);
            System.IO.StreamReader sr = new System.IO.StreamReader(sourceFilePath);
            Response.Write("Ok");
            string content = sr.ReadToEnd();
            // Assuming the Web Part Page template has a Title Bar Web Part with the title place holder "_TitlePlaceHolder_"
            content = content.Replace("_TitlePlaceHolder_", fileName);
            // Save the target file into the database
            fileName += ".aspx";

            string doclibID = onetidDocLibIDSelect.Value;
            Guid guidDocLib = new Guid(doclibID);
            SPList doclib = spWeb.Lists[guidDocLib];
            string folderPath = doclib.RootFolder.Url;
            string targetFilePath = spWeb.Url + "/" + folderPath + "/" + fileName;
            // Convert the string into UTF8 encoded bytes
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            System.Byte[] contentBytes = encoding.GetBytes(content);
            System.Byte[] bytes = new System.Byte[contentBytes.Length + 3];
            // Adding UTF8 byte order mark
            bytes[0] = 0xEF;
            bytes[1] = 0xBB;
            bytes[2] = 0xBF;
            contentBytes.CopyTo(bytes, 3);
            SPFileCollection fileCollection = spWeb.Files;
            if (OverwriteCheckBox.Checked)
            {
                SPFile spFile = spWeb.GetFile(targetFilePath);
                if (spFile != null && spFile.Exists)
                {
                    SPFolder spFolder = spWeb.GetFolder(folderPath);
                    spFolder.Files.Delete(targetFilePath);
                }
            }
            SPFile page = fileCollection.Add(targetFilePath, bytes);

            string strPageDisplayTitle = txtPageDisplayTitle.Text;
            if (!string.IsNullOrEmpty(strPageDisplayTitle))
            {
                try
                {
                    SPListItem item = page.Item;
                    item["PageDisplayTitle"] = strPageDisplayTitle;
                    item.Update();
                }
                catch (Exception)
                {

                    //throw;
                }

            }

            if (!string.IsNullOrEmpty(templateName))
            {
                try
                {
                    string strPageResponsiveTemplate = templateName;
                    SPListItem item = page.Item;
                    item["PageTemplate"] = strPageResponsiveTemplate;
                    item.Update();
                }
                catch (Exception)
                {

                    //throw;
                }

            }

            // Redirect to the newly created Web Part Page, with the toolpane opened in the Add Web Parts view
            Response.Redirect(targetFilePath + "?PageView=Shared&DisplayMode=Design&InitialTabId=Ribbon.WebPartPage&VisibilityContext=WSSWebPartPage");
        }
    }
}
